import { useState } from "react";

interface StreamData {
  id: number;
  message: string;
  timestamp: number;
}

interface StreamDataDisplayProps {}

export const StreamDataDisplay: React.FC<StreamDataDisplayProps> = () => {
  const [messages, setMessages] = useState<StreamData[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [count, setCount] = useState(5);
  const [delay, setDelay] = useState(1);

  const fetchStreamData = async () => {
    setLoading(true);
    setError(null);
    setMessages([]);

    try {
      const response = await fetch("http://localhost:5000/api/stream", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ count, delay }),
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error("Failed to get response reader");
      }

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = new TextDecoder().decode(value);
        const lines = chunk.split("\n").filter(Boolean);
        console.log("Received lines:", lines);

        lines.forEach((line) => {
          try {
            const data = JSON.parse(line);
            setMessages((prev) => [...prev, data]);
          } catch (e) {
            console.error("Failed to parse JSON:", e);
          }
        });
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="p-4 max-w-2xl mx-auto">
      <div className="mb-4 flex gap-4 items-center">
        <div>
          <label className="block text-sm font-medium text-gray-700">
            数据条数
          </label>
          <input
            type="number"
            value={count}
            onChange={(e) =>
              setCount(Math.max(1, parseInt(e.target.value) || 1))
            }
            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
            min="1"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-700">
            延迟时间(秒)
          </label>
          <input
            type="number"
            value={delay}
            onChange={(e) =>
              setDelay(Math.max(0.1, parseFloat(e.target.value) || 0.1))
            }
            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
            min="0.1"
            step="0.1"
          />
        </div>
        <button
          onClick={fetchStreamData}
          disabled={loading}
          className="mt-6 px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50"
        >
          {loading ? "加载中..." : "获取数据"}
        </button>
      </div>

      {error && (
        <div className="mb-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded">
          {error}
        </div>
      )}

      <div className="space-y-4">
        {messages.map((msg) => (
          <div
            key={msg.id}
            className="p-4 bg-white shadow rounded-lg border border-gray-200"
          >
            <div className="font-medium text-gray-900">{msg.message}</div>
            <div className="text-sm text-gray-500">
              {new Date(msg.timestamp * 1000).toLocaleString()}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};
